#include <stdio.h>
#include <unistd.h>
#include <fcntl.h>
#include <signal.h>
#include <string.h>
#include <stdlib.h>

int cnt, file_size;

// 打印拷贝进度
void sighandler(int signo)
{
    double rate = 100.0 * cnt / file_size;
    printf("拷贝进度:%0.0lf%%\n", rate);
}

void sigalarm(int signo)
{
    kill(getppid(),SIGUSR1);
}

int main()
{
    int src_file, dst_file, bytereads;
    pid_t pid;
    char buffer[1024] = {0};
    src_file = open("./src_file.txt", O_RDONLY);
    if (src_file < 0)
    {
        perror("file open failed");
        return 1;
    }
    dst_file = open("./dst_file.txt", O_CREAT | O_WRONLY, 0664);
    if (dst_file < 0)
    {
        perror("file open failed");
        return 1;
    }
    pid = fork();
    if (pid < 0)
    {
        perror("fork failed");
        return 1;
    }
    else if (pid == 0) // 子进程
    {
        // 子进程不断向父进程发送SIGUSR1信号
        // while(1)
        // {
        //     sleep(1);
        //     kill(getppid(), SIGUSR1);
        // }
        usleep(1);
        signal(SIGALRM,sigalarm);
        ualarm(1,1);
        while(1);
        exit(EXIT_SUCCESS);
    }
    else // 父进程
    {
        signal(SIGUSR1, sighandler);
        // 计算文件大小
        file_size = lseek(src_file, 0, SEEK_END);
        lseek(src_file, 0, SEEK_SET);
        // 进行拷贝
        while ((bytereads = read(src_file, buffer, sizeof(buffer))) > 0)
        {         
            write(dst_file, buffer, bytereads);
            cnt = lseek(src_file, 0, SEEK_CUR);
            memset(buffer,0,sizeof(buffer));
        }
    }
    close(src_file);
    close(dst_file);
    return 0;
}